<template>
  <div>
    <el-card class="activity-manag-edit" shadow="never">
      <template-form
        ref="form"
        v-loading="isLoading"
        class="activity-manag-edit__form"
        :configs="classCreateFields"
        :params="params"
        :data="editData"
      />
      <div class="activity-manag-edit__btn">
        <el-button @click="handleBack">返回</el-button>
        <el-button
          type="primary"
          :disabled="disableByFailed"
          :loading="isLoading"
          @click="beforeSubmit"
        >提交</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  createAndUpdate,
  detail
} from 'dependencies/api/templateClass'
import EditDataMixin from 'modules/mixins/edit-data'
import LoadingMixin from 'modules/mixins/section-loading'
import { classCreateFields } from './config'
import { parseTime } from '@/utils'

export default {
  mixins: [EditDataMixin, LoadingMixin],
  data() {
    return {
      _id: '',
      editData: {},
      classCreateFields: classCreateFields,
      disableByFailed: false,
      params: {
      }
    }
  },
  computed: {
    isEdit() {
      return !!this._id
    }
  },
  onLoad(options = {}) {
  	this._id = options._id
  	if (this._id) {
      this.getDetail()
  	}
  },
  methods: {
    async getDetail() {
      try {
        this.loading()
        const res = await detail({
          _id: this._id
        })
        this.params = {
          ...res.data
        }
        this.params.previewUrl = this.params.previewUrl[0]
      } catch (error) {
        this.params = {}
        this.disableByFailed = true
      } finally {
        this.loaded()
      }
    },
    beforeSubmit() {
      const params = this.$refs.form.submit()
      this.submit(params)
    },
    async submit(data) {
      // eslint-disable-next-line
      const { ...params } = data
      if (this.isEdit) {
        params._id = this._id
      }
      this.loading()
      try {
        params.previewUrl = [params.previewUrl]
        const data = await createAndUpdate(params)
        if (data.code === 0) {
          this.$message.success(`${this.isEdit ? '编辑' : '新增'}成功!`)
          setTimeout(() => {
            this.handleBack()
          }, 500)
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loaded()
      }
    },
    handleBack() {
      vk.navigateTo(`/pages/avatar-class/list`);
    }
  }
}
</script>

<style lang="scss" scoped>
.activity-manag-edit {
  display: flex;
  justify-content: center;
  &__form {
    width: 800px;
  }
  &__btn {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style>
<style lang="scss">
.ql-container {
  height: 300px;
}
</style>
